// wheel.js
const { getWheelById } = require('../../config/wheels.js')

Page({
  data: {
    // 转盘相关数据
    wheelConfig: {},
    options: [],
    rotation: 0,
    isSpinning: false,
    result: '',
    sectionAngle: 0,
    wheelBackground: '',
    isCustom: false,
    
    // 弹窗相关
    showModal: false,
    newOption: '',
    showSaveModal: false,
    wheelName: '',
    wheelDesc: '',
    
    // 转盘配置
    minSpinAngle: 1080,
    maxSpinAngle: 1800,
    spinDuration: 3000,
  },

  onLoad(options) {
    const wheelId = options.wheelId
    console.log('转盘ID:', wheelId)
    
    if (wheelId === 'custom') {
      this.initCustomWheel()
    } else if (wheelId.startsWith('custom_')) {
      this.initSavedWheel(wheelId)
    } else {
      this.initPresetWheel(wheelId)
    }
  },
  onShow() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },
  onShareAppMessage() {
    const title = this.data.wheelConfig.title || '转盘助手'
    const desc = this.data.wheelConfig.description || '来试试你的手气！'
    const wheelId = this.data.isCustom ? 'custom' : (this.data.wheelConfig.id || '')
    return {
      title: `${title} - ${desc}`,
      path: `/pages/wheel/wheel?wheelId=${wheelId}`
    }
  },
  onShareTimeline() {
    const title = this.data.wheelConfig.title || '转盘助手'
    return {
      title
    }
  },

  // 初始化预设转盘
  initPresetWheel(wheelId) {
    const wheelConfig = getWheelById(wheelId)
    if (!wheelConfig) {
      wx.showToast({
        title: '转盘不存在',
        icon: 'none'
      })
      wx.navigateBack()
      return
    }

    this.setData({
      wheelConfig: wheelConfig,
      options: wheelConfig.options,
      isCustom: false
    })

    this.calculateSectionAngle()
    this.updateWheelBackground()
  },

  // 初始化自定义转盘
  initCustomWheel() {
    this.setData({
      wheelConfig: {
        title: '自定义转盘',
        description: '创建你的专属转盘',
        icon: '🎯',
        color: '#667eea'
      },
      options: ['选项1', '选项2', '选项3', '选项4'],
      isCustom: true
    })

    this.calculateSectionAngle()
    this.updateWheelBackground()
    this.loadOptions()
  },

  // 初始化已保存的转盘
  initSavedWheel(wheelId) {
    const savedWheels = wx.getStorageSync('saved_wheels') || []
    const wheelConfig = savedWheels.find(wheel => wheel.id === wheelId)
    
    if (!wheelConfig) {
      wx.showToast({
        title: '转盘不存在',
        icon: 'none'
      })
      wx.navigateBack()
      return
    }

    this.setData({
      wheelConfig: wheelConfig,
      options: wheelConfig.options,
      isCustom: true
    })

    this.calculateSectionAngle()
    this.updateWheelBackground()
  },

  // 计算每个扇形的角度
  calculateSectionAngle() {
    const optionsCount = this.data.options.length
    if (optionsCount > 0) {
      this.setData({
        sectionAngle: 360 / optionsCount
      })
      this.updateWheelBackground()
    }
  },

  // 更新转盘背景
  updateWheelBackground() {
    const options = this.data.options
    if (options.length === 0) return

    const colors = ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#feca57', '#ff9ff3', '#54a0ff', '#5f27cd']
    const sectionAngle = this.data.sectionAngle
    
    console.log('更新转盘背景，选项数量:', options.length)
    console.log('每个扇形角度:', sectionAngle)
    
    let gradientString = ''
    options.forEach((option, index) => {
      const startAngle = index * sectionAngle
      const endAngle = (index + 1) * sectionAngle
      const color = colors[index % colors.length]
      console.log(`选项${index}: ${option}, 角度: ${startAngle}deg-${endAngle}deg, 颜色: ${color}`)
      gradientString += `${color} ${startAngle}deg ${endAngle}deg`
      if (index < options.length - 1) {
        gradientString += ', '
      }
    })

    console.log('生成的渐变字符串:', gradientString)

    this.setData({
      wheelBackground: `conic-gradient(${gradientString})`
    })
  },
  // 开始转盘
  startSpin() {
    if (this.data.options.length < 2) {
      wx.showToast({
        title: '至少需要2个选项',
        icon: 'none'
      })
      return
    }

    if (this.data.isSpinning) return

    this.setData({ isSpinning: true, result: '' })

    const randomAngle = Math.random() * (this.data.maxSpinAngle - this.data.minSpinAngle) + this.data.minSpinAngle
    const finalRotation = this.data.rotation + randomAngle

    this.setData({ rotation: finalRotation })

    setTimeout(() => {
      this.calculateResult(finalRotation)
    }, this.data.spinDuration)
  },

  // 计算转盘结果
  calculateResult(finalRotation) {
    const normalizedAngle = ((finalRotation % 360) + 360) % 360
    const sectionAngle = this.data.sectionAngle
    // conic-gradient 的 0° 在正右方，指针在正上方(270°)，因此需要 +90° 再取反
    const angleAtTop = (360 - ((normalizedAngle + 90) % 360)) % 360
    const adjustedIndex = Math.floor(angleAtTop / sectionAngle)
    
    console.log('转盘结果计算:')
    console.log('最终旋转角度:', finalRotation)
    console.log('标准化角度(相对右侧0°):', normalizedAngle)
    console.log('指针对应角度(相对右侧0°):', angleAtTop)
    console.log('扇形角度:', sectionAngle)
    console.log('最终索引:', adjustedIndex)
    
    const result = this.data.options[adjustedIndex]
    console.log('最终结果:', result)
    
    this.setData({
      result: result,
      isSpinning: false
    })

    wx.showToast({
      title: `结果：${result}`,
      icon: 'none',
      duration: 2000
    })
  },

  // 显示添加选项弹窗
  showAddOption() {
    console.log('显示添加选项弹窗')
    this.setData({ 
      showModal: true, 
      newOption: '' 
    })
    console.log('弹窗状态:', this.data.showModal)
  },

  // 隐藏添加选项弹窗
  hideAddOption() {
    this.setData({ showModal: false, newOption: '' })
  },

  // 显示保存转盘弹窗
  showSaveModal() {
    console.log('显示保存转盘弹窗')
    console.log('当前选项数量:', this.data.options.length)
    console.log('当前选项:', this.data.options)
    
    this.setData({ 
      showSaveModal: true, 
      wheelName: '',
      wheelDesc: ''
    })
  },

  // 隐藏保存转盘弹窗
  hideSaveModal() {
    this.setData({ 
      showSaveModal: false, 
      wheelName: '',
      wheelDesc: ''
    })
  },

  // 输入转盘名称
  onNameInput(e) {
    this.setData({ wheelName: e.detail.value })
  },

  // 输入转盘描述
  onDescInput(e) {
    this.setData({ wheelDesc: e.detail.value })
  },

  // 保存转盘
  saveWheel() {
    console.log('保存转盘被调用')
    const wheelName = this.data.wheelName.trim()
    const wheelDesc = this.data.wheelDesc.trim()
    
    console.log('转盘名称:', wheelName)
    console.log('转盘描述:', wheelDesc)
    console.log('当前选项:', this.data.options)
    
    if (!wheelName) {
      wx.showToast({
        title: '请输入转盘名称',
        icon: 'none'
      })
      return
    }

    if (this.data.options.length < 2) {
      wx.showToast({
        title: '至少需要2个选项',
        icon: 'none'
      })
      return
    }

    try {
      // 获取已保存的自定义转盘列表
      let savedWheels = wx.getStorageSync('saved_wheels') || []
      console.log('已保存的转盘数量:', savedWheels.length)
      
      // 创建新的转盘配置
      const newWheel = {
        id: 'custom_' + Date.now(),
        title: wheelName,
        description: wheelDesc || '自定义转盘',
        icon: '🎯',
        color: '#667eea',
        options: this.data.options,
        isCustom: true,
        createTime: new Date().toISOString()
      }

      console.log('新转盘配置:', newWheel)

      // 添加到保存列表
      savedWheels.push(newWheel)
      
      // 保存到本地存储
      wx.setStorageSync('saved_wheels', savedWheels)
      
      console.log('保存后的转盘列表:', savedWheels)
      
      this.hideSaveModal()
      
      wx.showToast({
        title: '保存成功',
        icon: 'success'
      })

      console.log('转盘已保存:', newWheel)
      
      // 刷新首页列表
      const pages = getCurrentPages()
      const prevPage = pages[pages.length - 2]
      if (prevPage && prevPage.route === 'pages/index/index') {
        console.log('刷新首页转盘列表')
        prevPage.loadWheelList()
      }
    } catch (error) {
      console.error('保存转盘失败:', error)
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      })
    }
  },

  // 输入选项内容
  onOptionInput(e) {
    this.setData({ newOption: e.detail.value })
  },

  // 添加选项
  addOption() {
    console.log('添加选项被调用')
    const newOption = this.data.newOption.trim()
    console.log('新选项内容:', newOption)
    console.log('当前选项列表:', this.data.options)
    
    if (!newOption) {
      wx.showToast({
        title: '请输入选项内容',
        icon: 'none'
      })
      return
    }

    if (this.data.options.includes(newOption)) {
      wx.showToast({
        title: '选项已存在',
        icon: 'none'
      })
      return
    }

    const newOptions = [...this.data.options, newOption]
    console.log('新的选项列表:', newOptions)
    
    this.setData({ 
      options: newOptions,
      showModal: false,
      newOption: ''
    })
    
    this.calculateSectionAngle()
    this.saveOptions()

    wx.showToast({
      title: '添加成功',
      icon: 'success'
    })
  },

  // 删除选项
  deleteOption(e) {
    const index = e.currentTarget.dataset.index
    const options = [...this.data.options]
    options.splice(index, 1)
    
    this.setData({ options: options })
    this.calculateSectionAngle()
    this.saveOptions()

    wx.showToast({
      title: '删除成功',
      icon: 'success'
    })
  },

  // 清空所有选项
  clearOptions() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空所有选项吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({ options: [] })
          this.calculateSectionAngle()
          this.saveOptions()
          
          wx.showToast({
            title: '已清空',
            icon: 'success'
          })
        }
      }
    })
  },

  // 保存选项到本地存储
  saveOptions() {
    if (this.data.isCustom) {
      wx.setStorageSync('custom_wheel_options', this.data.options)
    }
  },

  // 从本地存储加载选项
  loadOptions() {
    if (this.data.isCustom) {
      const savedOptions = wx.getStorageSync('custom_wheel_options')
      if (savedOptions && savedOptions.length > 0) {
        this.setData({ options: savedOptions })
        this.calculateSectionAngle()
      }
    }
  }
})
